package com.kevin.pay.service.impl;

import com.kevin.pay.config.WeChatConfig;
import com.kevin.pay.domain.User;
import com.kevin.pay.mapper.UserMapper;
import com.kevin.pay.service.UserService;
import com.kevin.pay.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User saveWeChatUser(String code) {

        String accessTokenUrl=String.format(WeChatConfig.getOpenAccessTokenUrl(),weChatConfig.getOpenAppid(),weChatConfig.getOpenAppSecret(),code);

        Map<String ,Object> baseMap= HttpUtils.doGet(accessTokenUrl);

        if (baseMap==null||baseMap.isEmpty()){
            return null;
        }

        String accessToken= (String) baseMap.get("access_token");
        String  openid= (String) baseMap.get("access_token");

        User dbUser=userMapper.findByopenid(openid);
        //FIXME 更新用户信息，再返回
        if (dbUser!=null){
            return dbUser;
        }

        String userInfoUrl=String.format(WeChatConfig.getOpenUserInfoUrl(),accessToken,openid);

        Map<String,Object> baseUserMap=HttpUtils.doGet(userInfoUrl);

        if(baseMap==null||baseMap.isEmpty()){return null;}

        String nickname= (String) baseUserMap.get("nickname");
        Double sexTemp  = (Double) baseUserMap.get("sex");
        int sex = sexTemp.intValue();
        String province = (String)baseUserMap.get("province");
        String city = (String)baseUserMap.get("city");
        String country = (String)baseUserMap.get("country");
        String headimgurl = (String)baseUserMap.get("headimgurl");

        StringBuilder sb=new StringBuilder(country).append("||").append(province).append("||").append(city);
        String finalAddress=sb.toString();

        try {
            nickname=new String(nickname.getBytes("ISO-8859-1"),"UTF-8");
            finalAddress = new String(finalAddress.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        User user = new User();
        user.setName(nickname);
        user.setHeadImg(headimgurl);
        user.setCity(finalAddress);
        user.setOpenid(openid);
        user.setSex(sex);
        user.setCreateTime(new Date());
        userMapper.save(user);

        return user;
    }
}
